package com.eqdd.yiqidian.ui.mine.renwu;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RenwuInfoActivityCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.RenwuCheckInfoResultBean;
import com.eqdd.yiqidian.bean.rebuild.RenwuInfoResultBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditCardBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.select.RichTextResult;
import com.eqdd.yiqidian.ui.select.SelectRichTextActivity;
import com.eqdd.yiqidian.ui.select.ShowRichTextActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okrx2.adapter.FlowableBody;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.subscribers.DisposableSubscriber;

public class RenwuInfoActivity extends BaseActivity {
    private RenwuInfoActivityCustom dataBinding;
    private int status;
    private String taskId;
    private ArrayList<Object> datas;
    private SlimAdapterEx slimAdapterEx;
    private RenwuInfoResultBean items;
    private Bundle bundle;
    private ArrayList<RenwuInfoResultBean.RenwuStaffBean> renwuStaffBeen;
    private RichTextResult richTextResult;
    private RenwuCheckInfoResultBean renwuCheckInfo;
    private int who;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_renwu_info);
        initTopTitleBar(View.VISIBLE, "任务详情");
    }

    private boolean checkParam() {
        if (dataBinding.rbAgree.isChecked()) {
            return true;
        } else if (dataBinding.rbReject.isChecked() && !TextUtils.isEmpty(dataBinding.etRemark.getText())) {
            return true;
        }
        return false;
    }

    @Override
    public void initData() {
        status = getIntent().getIntExtra(Config.STATUS, -1);
        taskId = getIntent().getStringExtra("taskId");
        who = getIntent().getIntExtra("who", -1);
        datas = new ArrayList<>();
        initTitle();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create()
                .register(R.layout.list_item_28, new SlimInjector<SlimEditHintBean>() {
                    @Override
                    public void onInject(SlimEditHintBean data, IViewInjector injector) {
                        injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_hint_content, dealText(data.getContent()));
                    }
                })
                .register(R.layout.list_item_29, new SlimInjector<SlimEditEnterBean>() {
                    @Override
                    public void onInject(SlimEditEnterBean data, IViewInjector injector) {
                        injector.text(R.id.tv_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_right_content, dealText(data.getContent()))
                                .with(R.id.tv_right_content, v -> ((TextView) v).setHint(dealText(data.getHintContent())));
                    }
                }).register(R.layout.list_item_35, new SlimInjector<SlimEditCardBean>() {
                    @Override
                    public void onInject(SlimEditCardBean data, IViewInjector injector) {
                        injector.text(R.id.tv_upper_left_content, data.getUpperLeftContent())
                                .text(R.id.tv_upper_right_content, dealText(data.getUpperRightContent()))
                                .text(R.id.tv_down_left_content, dealText(data.getTitle()))
                                .text(R.id.tv_down_right_content, dealText(data.getContent()));
                    }
                }).attachTo(dataBinding.recyclerView);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (slimAdapterEx.getDataItem(position) instanceof SlimEditBean) {
                        SlimEditBean slimBean = (SlimEditBean) slimAdapterEx.getDataItem(position);
                        switch (slimBean.getPosition()) {
                            case 1:
                                renwuStaffBeen = new ArrayList<>();
                                renwuStaffBeen.add(items.getNewInitiator());
                                bundle = new Bundle();
                                bundle.putParcelableArrayList("list", renwuStaffBeen);
                                startActivity(RenwuStaffListActivity.class, bundle);
                                break;
                            case 2:
                                renwuStaffBeen = new ArrayList<>();
                                renwuStaffBeen.add(items.getNewRecipient());
                                bundle = new Bundle();
                                bundle.putParcelableArrayList("list", renwuStaffBeen);
                                startActivity(RenwuStaffListActivity.class, bundle);
                                break;
                            case 3:
                                renwuStaffBeen = new ArrayList<>();
                                renwuStaffBeen.addAll(items.getNewNotify());
                                bundle = new Bundle();
                                bundle.putParcelableArrayList("list", renwuStaffBeen);
                                startActivity(RenwuStaffListActivity.class, bundle);
                                break;
                            case 4:
                                renwuStaffBeen = new ArrayList<>();
                                renwuStaffBeen.addAll(items.getNewAssist());
                                bundle = new Bundle();
                                bundle.putParcelableArrayList("list", renwuStaffBeen);
                                startActivity(RenwuStaffListActivity.class, bundle);
                                break;
                            case 5:
                                renwuStaffBeen = new ArrayList<>();
                                renwuStaffBeen.add(items.getNewChecker());
                                bundle = new Bundle();
                                bundle.putParcelableArrayList("list", renwuStaffBeen);
                                startActivity(RenwuStaffListActivity.class, bundle);
                                break;
                            case 8:
                                bundle = new Bundle();
                                bundle.putString("title", slimBean.getTitle());
                                bundle.putString("content", items.getCheckStandard());
                                startActivity(TextActivity.class, bundle);
                                break;
                            case 10:
                                bundle = new Bundle();
                                bundle.putString("title", slimBean.getTitle());
                                bundle.putString("content", items.getDuty());
                                startActivity(TextActivity.class, bundle);
                                break;
                            case 11:
                                Bundle bundle = new Bundle();
                                bundle.putString("content", slimBean.getContent());
                                bundle.putString("title", "详情");
                                startActivity(TextActivity.class, bundle);
                                break;
                            case 12:
                                enterShowRichActivity(items.getCompleteMessage(), slimBean.getTitle(), items.getCompleteImageUrls());
                                break;
                            case 13:
                                enterShowRichActivity(renwuCheckInfo.getCheckMessage(), slimBean.getTitle(), renwuCheckInfo.getImageUrls());
                                break;

                        }
                    }
                });
        dataBinding.rbReject.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbAgree.setChecked(!isChecked);
            }
        });
        dataBinding.rbAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                dataBinding.rbReject.setChecked(!isChecked);
            }
        });
    }

    private void enterShowRichActivity(String content, String title, List<String> urls) {
        RichTextResult richTextResult = new RichTextResult();
        ArrayList<LocalMedia> localMedias = new ArrayList<>();
        richTextResult.setSelectMedia(localMedias);
        richTextResult.setContent(content);
        if (urls != null) {
            for (int i = 0; i < urls.size(); i++) {
                richTextResult.getSelectMedia().add(new LocalMedia(urls.get(i), 0, PictureMimeType.ofImage(), PictureConfig.IMAGE));
            }
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable(Config.RICH_TEXT_RESULT, richTextResult);
        bundle.putString(Config.TITLE, title);
        startActivity(ShowRichTextActivity.class, bundle);
    }

    private void initTitle() {
        if (who == Config.ZERENREN && status == 0) {
            initTopRightText("提交", v -> {
                if (checkParam()) {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + (dataBinding.rbAgree.isChecked() ? HttpConfig.ACCEPT_RENWU : HttpConfig.REJECT_RENWU))
                            .params("userGuid", user.getGuid())
                            .params("taskId", items.getId())
                            .params("message", TextUtils.isEmpty(dataBinding.etRemark.getText().toString()) ? "无备注信息" : dataBinding.etRemark.getText().toString())
                            .params("name", user.getName())
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        setResult(Config.SUCCESS);
                                        finish();
                                    }
                                }
                            });
                } else {
                    ToastUtil.showShort("被拒绝好可怜，添加备注说明一下原因嘛！");
                }
            });
        } else if (who == Config.ZERENREN && status == 1) {
            initTopRightText("完成", v -> {
                Bundle bundle = new Bundle();
                bundle.putString("title", "任务完成描述");
                bundle.putSerializable(Config.RICH_TEXT_RESULT, richTextResult);
                startActivityForResult(SelectRichTextActivity.class, bundle, Config.SELECT_RICH_TEXT);
            });
        } else if (who == Config.YANSHOUREN && status == 0) {
            initTopRightText("验收", v -> {
                Bundle bundle = new Bundle();
                bundle.putString("title", "验收结果描述");
                bundle.putSerializable(Config.RICH_TEXT_RESULT, richTextResult);
                startActivityForResult(SelectRichTextActivity.class, bundle, Config.SELECT_RICH_TEXT);
            });
        }
//        switch (type) {
//            case 1://责任人新任务
//
//                break;
//            case 2://责任人完成任务
//                initTopRightText("完成", v -> {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("title", "任务完成描述");
//                    bundle.putSerializable(Config.RICH_TEXT_RESULT, richTextResult);
//                    startActivityForResult(SelectRichTextActivity.class, bundle, Config.SELECT_RICH_TEXT);
//                });
//                break;
//            case 5://验收人验收任务任务
//
//                break;
//        }
    }

    @Override
    public void setView() {

        showLoading();
        Flowable<HttpResult<RenwuInfoResultBean>> renwuInfoFlow = OkGo.<HttpResult<RenwuInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.RENWU_INFO)
                .params("taskId", this.taskId)
                .converter(new JsonConverter<HttpResult<RenwuInfoResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<RenwuInfoResultBean>>());
        Flowable<HttpResult<RenwuCheckInfoResultBean>> renwuCheckInfoFlow = OkGo.<HttpResult<RenwuCheckInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.RENWU_CHECK_INFO)
                .params("taskId", this.taskId)
                .converter(new JsonConverter<HttpResult<RenwuCheckInfoResultBean>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<HttpResult<RenwuCheckInfoResultBean>>());
        Flowable.combineLatest(renwuInfoFlow, renwuCheckInfoFlow, new BiFunction<HttpResult<RenwuInfoResultBean>, HttpResult<RenwuCheckInfoResultBean>, Object>() {
            @Override
            public Object apply(@NonNull HttpResult<RenwuInfoResultBean> renwuInfoResultBeanHttpResult, @NonNull HttpResult<RenwuCheckInfoResultBean> renwuCheckInfoResultBeanHttpResult) throws Exception {
                items = renwuInfoResultBeanHttpResult.getItems();
                renwuCheckInfo = renwuCheckInfoResultBeanHttpResult.getItems();
                datas.add(new SlimEditHintBean("任务名称", RenwuInfoActivity.this.items.getTaskName(), 0));
                if (who != Config.FABUREN && who != Config.CANYUREN) {
                    datas.add(new SlimEditEnterBean("发布人", RenwuInfoActivity.this.items.getNewInitiator().getName(), 1, true, ""));
                }
                if (who != Config.ZERENREN) {
                    datas.add(new SlimEditEnterBean("责任人", RenwuInfoActivity.this.items.getNewRecipient().getName(), 2, true, ""));
                }
                if (who == Config.FABUREN) {
                    datas.add(new SlimEditEnterBean("知会人", RenwuInfoActivity.this.items.getNewNotify().size() + "人", 3, true, ""));
                }
                if (who == Config.ZERENREN || who == Config.FABUREN) {
                    datas.add(new SlimEditEnterBean("协助人", RenwuInfoActivity.this.items.getNewAssist().size() + "人", 4, true, ""));
                }
                if (who == Config.FABUREN) {
                    datas.add(new SlimEditEnterBean("验收人", RenwuInfoActivity.this.items.getNewChecker().getName(), 5, true, ""));
                }
                if (who != Config.YANSHOUREN) {
                    datas.add(new SlimEditHintBean("开始时间", RenwuInfoActivity.this.items.getStartTime(), 6));
                    datas.add(new SlimEditHintBean("结束时间", RenwuInfoActivity.this.items.getEndTime(), 7));
                }
                if (who != Config.CANYUREN) {
                    datas.add(new SlimEditEnterBean("验收标准", RenwuInfoActivity.this.items.getCheckStandard(), 8, true, ""));
                }
                if (who == Config.FABUREN || who == Config.YANSHOUREN) {
                    datas.add(new SlimEditHintBean("验收时间", RenwuInfoActivity.this.items.getCheckTime(), 9));
                }
                if (who != Config.YANSHOUREN) {
                    datas.add(new SlimEditEnterBean("任务描述", RenwuInfoActivity.this.items.getTaskDesc(), 10, true, ""));
                }

                if (who == Config.ZERENREN && status == 0) {
                    dataBinding.ll1.setVisibility(View.VISIBLE);
                } else if (who == Config.ZERENREN && status == 1) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                } else if (who == Config.ZERENREN && status == 3) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                    if (items.getStatus() == 3) {
                        datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
                    }
                    if (renwuCheckInfo != null) {
                        datas.add(new SlimEditCardBean("验收任务图文", renwuCheckInfo.getCheckMessage(), 13, "验收人", "点击查看详情"));
                    }
                } else if (who == Config.FABUREN && status == 0) {

                } else if (who == Config.FABUREN && status == 1) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));

                } else if (who == Config.FABUREN && status == 2) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                } else if (who == Config.FABUREN && status == 3) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                    if (items.getStatus() == 3) {
                        datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
                    }
                    if (renwuCheckInfo != null) {
                        datas.add(new SlimEditCardBean("验收任务图文", renwuCheckInfo.getCheckMessage(), 13, "验收人", "点击查看详情"));
                    }
                } else if (who == Config.CANYUREN && status == 1) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));

                } else if (who == Config.CANYUREN && status == 3) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                    if (items.getStatus() == 3) {
                        datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
                    }
                    if (renwuCheckInfo != null) {
                        datas.add(new SlimEditCardBean("验收任务图文", renwuCheckInfo.getCheckMessage(), 13, "验收人", "点击查看详情"));
                    }
                } else if (who == Config.YANSHOUREN && status == 0) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                    if (items.getStatus() == 3) {
                        datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
                    }
                } else if (who == Config.YANSHOUREN && status == 1) {
                    datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
                    if (items.getStatus() == 3) {
                        datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
                    }
                    if (renwuCheckInfo != null) {
                        datas.add(new SlimEditCardBean("验收任务图文", renwuCheckInfo.getCheckMessage(), 13, "验收人", "点击查看详情"));
                    }
                }
//                switch (type) {
//                    case 0:
//                        break;
//                    case 1://责任人新任务
//                        dataBinding.ll1.setVisibility(View.VISIBLE);
//                        break;
//                    case 2://责任人完成任务
//                        datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
//                        break;
//                    case 3://责任人接受任务，查看任务详情
//                        datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
//                        break;
//                    case 4:
//                        datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
//                        datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
//                        break;
//                    case 5:
//                        datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
//                        if (items.getStatus() == 3) {
//                            datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
//                        }
//                        break;
//                    case 6:
//                        datas.add(new SlimEditCardBean("备注", items.getOptionMessage(), 11, "责任人", "点击查看详情"));
//                        if (items.getStatus() == 3) {
//                            datas.add(new SlimEditCardBean("完成任务图文", items.getCompleteMessage(), 12, "责任人", "点击查看详情"));
//                        }
//                        datas.add(new SlimEditCardBean("验收任务图文", renwuCheckInfo.getCheckMessage(), 13, "验收人", "点击查看详情"));
//                        break;
//                    case 7:
//                        if (items.isCheck()) {
//                            datas.add(new SlimEditCardBean("验收任务图文", renwuCheckInfo.getCheckMessage(), 13, "验收人", "点击查看详情"));
//                        }
//                        break;
//                }
                return 1;
            }
        })
                .subscribe(disposableSubscriber);
    }

    private DisposableSubscriber disposableSubscriber = new DisposableSubscriber<Object>() {

        @Override
        public void onNext(Object o) {
            slimAdapterEx.updateData(datas);
        }

        @Override
        public void onError(Throwable t) {
            hideLoading();
            System.out.println(t.toString());
            ToastUtil.showShort(Config.SERVER_ERROR);
        }

        @Override
        public void onComplete() {
            hideLoading();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!disposableSubscriber.isDisposed()) {
            disposableSubscriber.dispose();
        }
    }

    private String dealText(String text) {
        return TextUtils.isEmpty(text) ? "" : text;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.SELECT_RICH_TEXT:
                    richTextResult = (RichTextResult) data.getSerializableExtra(Config.RICH_TEXT_RESULT);
                    PostRequest<HttpResult> params = OkGo.<HttpResult>post(HttpConfig.BASE_URL + ((who == Config.ZERENREN && status == 1) ? HttpConfig.FINISH_RENWU : HttpConfig.CHECK_RENWU))
                            .params("userGuid", user.getGuid())
                            .params("taskId", items.getId())
                            .params("message", richTextResult.getContent())
                            .params("name", user.getName());
                    List<LocalMedia> selectMedia = richTextResult.getSelectMedia();
                    for (int i = 0; i < selectMedia.size(); i++) {
                        params.params("file", new File(selectMedia.get(i).isCompressed() ? selectMedia.get(i).getCompressPath() : selectMedia.get(i).getPath()));
                    }
                    params.execute(new DialogCallBack<HttpResult>(this) {
                        @Override
                        public void onSuccess(Response<HttpResult> response) {
                            HttpResult httpResult = response.body();
                            ToastUtil.showShort(httpResult.getMsg());
                            if (httpResult.getStatus() == 200) {
                                finish();
                            }
                        }
                    });
            }
        }
    }
}
